//
//  AdView.swift
//  HLDesktop
//
//  Created by 子凡 on 2025/4/10.
//

import UIKit

class AdView: UIView {

    var adImageView:UIImageView?
    var tapBlock: os_block_t?
    
    deinit {
        print("没有循环引用才会触发:AdView.deinit")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.initUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initUI(){
        self.backgroundColor = .red
        adImageView = UIImageView(frame: self.frame)
        if let adImgView = adImageView{
            adImgView.isUserInteractionEnabled = true
            adImgView.contentMode = .scaleAspectFill
            adImgView.clipsToBounds = true
            adImgView.setImageWithStr(imgurl: "IMG_9912.GIF")
            self.addSubview(adImgView)
        }
        let tapGes = UITapGestureRecognizer(target: self, action: #selector(tapAdView))
        self.addGestureRecognizer(tapGes)
        self.show()
        self.perform(#selector(tapAdView), with: nil, afterDelay: 3.0)
    }
    
    @objc func tapAdView(){
        NSObject.cancelPreviousPerformRequests(withTarget: self)
        self.tapBlock?()
    }
    
    func show(){
//UIApplication.shared.keyWindow?.addSubview(self)
        
//'keyWindow' was deprecated in iOS 13.0,改为:
        UIApplication.shared.windows.filter{$0.isKeyWindow}.first?.addSubview(self)
//或：
//        UIApplication.shared.windows.first { $0.isKeyWindow }?.addSubview(self)
        
    }

}

